<template>
  <div class="file-manager-container">
    <!-- 页面头部 -->
    <div class="page-header">
      <h2>文件管理</h2>
      <div class="header-actions">
        <el-upload
          :show-file-list="false"
          :before-upload="handleFileUpload"
          :on-error="handleUploadError"
          :on-success="handleUploadSuccess"
          action=""
          accept="*/*"
          multiple
        >
          <el-button type="primary" :icon="UploadFilled">
            上传文件
          </el-button>
        </el-upload>
      </div>
    </div>

    <!-- 搜索区域 -->
    <div class="search-filter">
      <el-input
        v-model="searchName"
        placeholder="请输入文件名搜索"
        style="width: 300px;"
        prefix-icon="Search"
        @keyup.enter="loadFileList"
      />
      <el-button type="primary" style="margin-left: 10px;" @click="loadFileList">
        搜索
      </el-button>
      <el-button style="margin-left: 10px;" @click="resetSearch">
        重置
      </el-button>
    </div>

    <!-- 文件列表 -->
    <el-table
      v-loading="loading"
      :data="fileList.records"
      border
      style="width: 100%; background-color: #fff;"
      row-key="id"
    >
      <el-table-column type="selection" width="50" />
      <el-table-column prop="id" label="文件ID" width="80" />
      <el-table-column prop="name" label="文件名" width="300" show-overflow-tooltip>
        <template #default="scope">
          <span>{{ scope.row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="type" label="文件类型" width="120" />
      <el-table-column prop="size" label="文件大小" width="120">
        <template #default="scope">
          {{ formatFileSize(scope.row.size) }}
        </template>
      </el-table-column>
      <el-table-column prop="enable" label="是否启用" width="100" />
      <el-table-column prop="isDelete" label="是否删除" width="100" />
      <el-table-column prop="md5" label="MD5值" width="300" show-overflow-tooltip />
      <el-table-column label="操作" width="180" fixed="right">
        <template #default="scope">
          <el-button type="primary" link @click="handleFileDownload(scope.row)">
            下载
          </el-button>
          <el-button type="danger" link @click="handleDelete(scope.row.id)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="fileList.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { ElMessage, ElMessageBox, ElUpload } from 'element-plus';
import { UploadFilled, Search } from '@element-plus/icons-vue';

// 定义文件类型
interface FileItem {
  id: number;
  name: string;
  type: string;
  size: number;
  url: string;
  isDelete: number;
  enable: number;
  md5: string;
}

// 模拟数据
const mockFiles: FileItem[] = [
  {
    id: 1,
    name: '产品介绍文档.pdf',
    type: 'application/pdf',
    size: 2560000, // 2.5MB
    url: '',
    isDelete: 0,
    enable: 1,
    md5: 'e8d4a0e4c308a4b8c9e2d3f1a0b1c2d3'
  },
  {
    id: 2,
    name: '项目规划.xlsx',
    type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
    size: 1200000, // 1.2MB
    url: '',
    isDelete: 0,
    enable: 1,
    md5: 'f9e8d7c6b5a4938271605f4e3d2c1b0a'
  },
  {
    id: 3,
    name: '设计稿.png',
    type: 'image/png',
    size: 3800000, // 3.8MB
    url: '',
    isDelete: 0,
    enable: 1,
    md5: 'a1b2c3d4e5f6071829304a5b6c7d8e9f'
  },
  {
    id: 4,
    name: '会议记录.docx',
    type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
    size: 850000, // 0.85MB
    url: '',
    isDelete: 0,
    enable: 1,
    md5: '1a2b3c4d5e6f7g8h9i0j1k2l3m4n5o6p'
  },
  {
    id: 5,
    name: '系统架构图.svg',
    type: 'image/svg+xml',
    size: 450000, // 0.45MB
    url: '',
    isDelete: 0,
    enable: 1,
    md5: '9z8y7x6w5v4u3t2s1r0q9p8o7n6m5l4k'
  }
];

// 文件列表数据
const fileList = ref({ records: [] as FileItem[], total: 0 });
const loading = ref(false);
const currentPage = ref(1);
const pageSize = ref(10);

// 搜索条件
const searchName = ref('');

// 组件挂载时加载数据
onMounted(() => {
  loadFileList();
});

// 加载文件列表
const loadFileList = async () => {
  loading.value = true;
  
  // 模拟网络延迟
  await new Promise(resolve => setTimeout(resolve, 300));
  
  try {
    // 过滤和分页逻辑
    let filteredFiles = [...mockFiles];
    
    // 应用搜索条件
    if (searchName.value) {
      const searchTerm = searchName.value.toLowerCase();
      filteredFiles = filteredFiles.filter(file => 
        file.name.toLowerCase().includes(searchTerm)
      );
    }
    
    // 应用分页
    const total = filteredFiles.length;
    const startIndex = (currentPage.value - 1) * pageSize.value;
    const endIndex = startIndex + pageSize.value;
    const paginatedFiles = filteredFiles.slice(startIndex, endIndex);
    
    // 更新文件列表
    fileList.value = {
      records: paginatedFiles,
      total: total
    };
    
  } catch (error) {
    ElMessage.error('加载文件列表失败');
    console.error('加载文件列表错误:', error);
  } finally {
    loading.value = false;
  }
};

// 处理文件上传
const handleFileUpload = async (rawFile: File) => {
  loading.value = true;
  
  // 模拟网络延迟
  await new Promise(resolve => setTimeout(resolve, 800));
  
  try {
    // 检查文件类型（这里可以根据需要添加更多限制）
    const isAllowed = true; // 简化处理，实际项目中可以添加文件类型和大小检查
    
    if (!isAllowed) {
      ElMessage.error('不支持的文件类型或大小超过限制');
      return false;
    }
    
    // 创建新的文件记录
    const newFile: FileItem = {
      id: Date.now(), // 使用时间戳作为临时ID
      name: rawFile.name,
      type: rawFile.type || 'application/octet-stream',
      size: rawFile.size,
      url: '', // 模拟环境下URL为空
      isDelete: 0,
      enable: 1,
      md5: 'mock-md5-' + Math.random().toString(36).substr(2, 9) // 生成随机MD5
    };
    
    // 添加到模拟数据中
    mockFiles.unshift(newFile);
    
    ElMessage.success('文件上传成功');
    loadFileList(); // 刷新列表
    
  } catch (error) {
    ElMessage.error('文件上传失败');
    console.error('文件上传错误:', error);
    return false;
  } finally {
    loading.value = false;
  }
};

// 处理上传错误
const handleUploadError = (error: any) => {
  ElMessage.error('文件上传失败');
  console.error('文件上传错误:', error);
  loading.value = false;
};

// 处理上传成功
const handleUploadSuccess = (response: any) => {
  ElMessage.success('文件上传成功');
  loadFileList();
};

// 处理文件下载
const handleFileDownload = (file: FileItem) => {
  try {
    // 模拟下载
    // 在真实环境中，这里会调用后端API下载文件
    // 在模拟环境中，我们只显示一个成功消息
    
    // 创建一个模拟的Blob对象作为文件内容
    const fileContent = `这是${file.name}的模拟内容。\n\n在实际应用中，这里会包含真实的文件数据。`;
    const blob = new Blob([fileContent], { type: file.type });
    const url = window.URL.createObjectURL(blob);
    
    // 创建下载链接并触发下载
    const link = document.createElement('a');
    link.href = url;
    link.download = file.name;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    
    // 释放URL对象
    window.URL.revokeObjectURL(url);
    
    ElMessage.success('文件下载成功');
    
  } catch (error) {
    ElMessage.error('文件下载失败');
    console.error('文件下载错误:', error);
  }
};

// 处理删除文件
const handleDelete = async (id: number) => {
  try {
    await ElMessageBox.confirm('确定要删除这个文件吗？', '确认删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });
    
    // 从模拟数据中删除文件
    const index = mockFiles.findIndex(file => file.id === id);
    if (index !== -1) {
      mockFiles.splice(index, 1);
      ElMessage.success('文件删除成功');
      loadFileList(); // 刷新列表
    } else {
      ElMessage.error('文件不存在');
    }
    
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('文件删除失败');
      console.error('文件删除错误:', error);
    }
  }
};

// 处理分页大小变化
const handleSizeChange = (size: number) => {
  pageSize.value = size;
  loadFileList();
};

// 处理当前页码变化
const handleCurrentChange = (current: number) => {
  currentPage.value = current;
  loadFileList();
};

// 格式化文件大小
const formatFileSize = (bytes: number): string => {
  if (bytes === 0) return '0 B';
  
  const k = 1024;
  const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
};

// 重置搜索条件
const resetSearch = () => {
  searchName.value = '';
  loadFileList();
};
</script>

<style scoped>
.file-manager-container {
  width: 100%;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  font-size: 24px;
  color: #333;
}

.search-filter {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #fff;
  border-radius: 4px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.header-actions {
  display: flex;
  gap: 10px;
}
</style>